# -*- coding: utf-8 -*-

from fire_control_spider.utils import ContentProcessor
from bs4 import BeautifulSoup
from .common import update_media_urls
from ..base_parser import BasePageParser


class LogGuideLineParser(BasePageParser):
    """新闻详情页解析器"""
    
    def __init__(self, spider):
        super().__init__(spider)
        self.site_name = 'iaff'
        self.categorys = ['Home', 'Newsroom', 'Press Kit', 'About the IAFF', 'IAFF Logo']
        
    
    def can_handle(self, response):
        """判断是否为新闻详情页"""
        return response.url == 'https://www.iaff.org/logo-guidelines/'
    
    def parse(self, response):
        """解析新闻详情页"""
        self.logger.info(f"开始处理详情页 {response.url}")
        
        # 创建基础item
        item = self.create_webpage_item(response)
        
        # 使用BeautifulSoup提取标题
        soup = BeautifulSoup(response.text, 'html.parser')
        
        # 提取菜单信息
        item['category'] = self.categorys
        
        title = ''
        # 尝试多种标题选择器
        title_selectors = ['h1']
        for selector in title_selectors:
            title_element = soup.select_one(selector)
            if title_element:
                title = title_element.get_text(strip=True)
                break
        
        if title:
            item['title'] = title
        
        item['publish_time'] = ''
        
        
        # 提取正文内容并处理图文交错
        main_content = self._extract_main_content(soup)
        if main_content:
            main_body, media_urls = ContentProcessor.process_content_with_media(
                main_content, response.url, self.site_name
            )
            item['main_body'] = main_body

            # 更新媒体URLs
            update_media_urls(item, media_urls)

        
        # 添加新闻特有信息
        item['remark'] = {}
        
        yield item
    

    
    def _extract_main_content(self, soup):
        """提取主要内容"""
        # 根据IAFF网站的具体结构提取内容
        # 这里需要根据实际网站结构调整选择器
        selectors = ['main']
        
        for selector in selectors:
            content_element = soup.select_one(selector)
            if content_element:
                return str(content_element)
    
        return ''
    